package leetcode_1_200;

import java.util.ArrayList;
import java.util.List;

public class LeeCode_151 {
    public static void main(String[] args) {
        System.out.println(reverseWords("the sky is blue"));
        System.out.println(reverseWords("blue"));
    }
    private static String reverseWords(String s) {
        StringBuilder ans = new StringBuilder();
        List<String> words = new ArrayList<>();
        boolean flag = false;
        StringBuilder word = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (!flag && c != ' '){
                flag = true;
            }
            if (flag){
                if (c == ' '){
                    flag = false;
                    words.add(word.toString());
                    word = new StringBuilder();
                }
            }
            if (flag){
                word.append(c);
                if (i == s.length() - 1)
                    words.add(word.toString());
            }
        }
        for (int i = words.size() - 1; i >= 0; i--) {
            ans.append(words.get(i));
            if (i != 0){
                ans.append(' ');
            }
        }
        return ans.toString();
    }
}
